package com.lagou.service.impl;

import com.lagou.service.EmailService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @ClassName: EmailServiceImpl
 * @Auther: Jerry
 * @Date: 2020/10/22 16:39
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Service
public class EmailServiceImpl implements EmailService {

    private Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Value("${mail_site_name}")
    private String mailSiteName;

    private static final String EMAIL_TITLE = "您正在使用邮箱安全验证服务";

    @Resource
    private JavaMailSender mailSender;

    @Autowired
    private TaskExecutor taskExecutor;

    @Override
    public Boolean sendToEmail(String email, String code) {
        try {
            logger.info("request param[{}], [{}]", email, code);
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            // 发送者
            helper.setFrom(mailSiteName);
            // 接收者
            helper.setTo(email);
            // 邮件标题
            helper.setSubject(EMAIL_TITLE);
            helper.setText(code);
            // 异步执行
            taskExecutor.execute(()->mailSender.send(mimeMessage));
            logger.info("email: {} send success", email);
            return true;
        } catch (MessagingException e) {
            logger.error(e.getMessage(), e);
            return false;
        } catch (Exception e) {
            return false;
        }
    }

}
